#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./paas/app/models.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import time, os
from django.db import models
from django.conf import settings
from django.db.models.deletion import SET_NULL
from app.constants import STATE_CHOICES, STATE_CHOICES_DISPALY_DICT, LANGUAGE_CHOICES, VCS_TYPE_CHOICES, DB_TYPE_CHOICES
APP_LOGO_IMG_RELATED = 'applogo'
SAAS_APP_LOGO_IMG_RELATED = 'saaslogo'

class AppTags(models.Model):
    """
    应用所属分类
    """
    name = models.CharField(u'分类名称', max_length=20, unique=True)
    code = models.CharField(u'分类英文ID', max_length=30, unique=True)
    index = models.IntegerField(u'排序', default=0, help_text=u'降序排序，即 9 在 0 之前')

    def __unicode__(self):
        return '%s(%s)' % (self.code, self.name)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('-index', )
        db_table = 'paas_apptags'
        verbose_name = u'应用分类信息'
        verbose_name_plural = u'应用分类信息'


class App(models.Model):
    """
    应用基本信息表
    """
    name = models.CharField(u'应用名称', max_length=20, unique=True)
    code = models.CharField(u'应用编码', max_length=30, unique=True, help_text=u'此处请用英文字母')
    introduction = models.TextField(u'应用简介')
    creater = models.CharField(u'创建者', max_length=20)
    created_date = models.DateTimeField(u'创建时间', auto_now_add=True, blank=True, null=True, db_index=True)
    state = models.SmallIntegerField(u'应用开发状态', choices=STATE_CHOICES, help_text=u'app的开发状态', default=1)
    tags = models.ForeignKey(AppTags, help_text=u'应用分类', blank=True, null=True, on_delete=SET_NULL)
    is_already_test = models.BooleanField(u'是否已经提测', default=False, help_text=u'app在测试环境下架或者开发中状态，修改该字段为False。')
    is_already_online = models.BooleanField(u'是否已经上线', default=False, help_text=u'app正式环境未下架，该字段为True。')
    first_test_time = models.DateTimeField(u'应用首次提测时间', help_text=u'记录应用首次提测时间', blank=True, null=True, db_index=True)
    first_online_time = models.DateTimeField(u'应用首次上线时间', help_text=u'记录应用首次上线时间', blank=True, null=True, db_index=True)
    developer = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=u'开发者', related_name='developers')
    language = models.CharField(u'语言', choices=LANGUAGE_CHOICES, default='python', max_length=50, blank=True, null=True)
    is_use_celery = models.BooleanField(u'app是否使用celery', default=False, help_text=u'选项: true(是)，false(否)')
    is_use_celery_beat = models.BooleanField(u'app是否使用定时任务', default=False, help_text=u'选项: true(是)，false(否)')
    auth_token = models.CharField('Token', max_length=36, blank=True, null=True)
    deploy_token = models.TextField('deploy_token', blank=True, null=True)
    is_saas = models.BooleanField('是否为SaaS服务', default=False, help_text=u'SaaS服务，即通过直接上传包部署')
    logo = models.ImageField(upload_to=APP_LOGO_IMG_RELATED, blank=True, null=True)

    def _del_exist_file(self, name):
        _file = os.path.join(settings.MEDIA_ROOT, name)
        if os.path.exists(_file):
            os.remove(_file)

    def save(self, *args, **kwargs):
        """
        保存前修改 logo 存放路径
        """
        if not self.logo:
            return super(App, self).save(*args, **kwargs)
        logo_ext = '.png'
        if self.logo.name.find('\\') >= 0:
            logo_name = APP_LOGO_IMG_RELATED + '\\' + str(self.code) + logo_ext
        else:
            if self.logo.name.find('/') >= 0:
                logo_name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
            else:
                logo_name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
        if cmp(logo_name, self.logo.name):
            logo_name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
            self._del_exist_file(logo_name)
            self.logo.name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
        super(App, self).save(*args, **kwargs)

    @property
    def get_logo_url(self):
        if self.logo:
            return '%s?v=%s' % (self.logo.url, time.time())
        logo_name = '%s/%s.png' % (APP_LOGO_IMG_RELATED, self.code)
        logo_path = os.path.join(settings.MEDIA_ROOT, logo_name)
        if os.path.exists(logo_path):
            return '%s%s' % (settings.MEDIA_URL, logo_name)
        logo_name = '%s/%s.png' % (SAAS_APP_LOGO_IMG_RELATED, self.code)
        logo_path = os.path.join(settings.MEDIA_ROOT, logo_name)
        if os.path.exists(logo_path):
            return '%s%s' % (settings.MEDIA_URL, logo_name)
        return '%simg/app_logo/default.png' % settings.STATIC_URL

    @property
    def state_display(self):
        return STATE_CHOICES_DISPALY_DICT.get(self.state)

    @property
    def saas_state_display(self):
        if self.state == 1:
            return u'未部署'
        return STATE_CHOICES_DISPALY_DICT.get(self.state)

    @property
    def created_date_display(self):
        if not self.created_date:
            return self.created_date
        return self.created_date.strftime('%Y-%m-%d')

    @property
    def first_test_time_display(self):
        if not self.first_test_time:
            return self.first_test_time
        return self.first_test_time.strftime('%Y-%m-%d %H:%M:%S')

    @property
    def first_online_time_display(self):
        if not self.first_online_time:
            return self.first_online_time
        return self.first_online_time.strftime('%Y-%m-%d %H:%M:%S')

    @property
    def introduction_display(self):
        if not self.introduction:
            return self.introduction
        return self.introduction.replace('\n', '<br/>')

    @property
    def app_test_url(self):
        return settings.APP_TEST_URL.format(app_code=self.code)

    @property
    def app_pro_url(self):
        return settings.APP_PROD_URL.format(app_code=self.code)

    def __unicode__(self):
        return '%s(%s)' % (self.code, self.name)

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'paas_app'
        verbose_name = u'应用基本信息'
        verbose_name_plural = u'应用基本信息'


class SecureInfo(models.Model):
    """
    APP 安全验证相关信息
    """
    app_code = models.CharField(u'对应的appcode', max_length=30, unique=True)
    vcs_type = models.SmallIntegerField(u'版本控制类型', choices=VCS_TYPE_CHOICES, help_text=u'app的开发状态', default=1)
    vcs_url = models.CharField(u'版本库URL', max_length=1024, blank=True, null=True)
    vcs_username = models.CharField(u'版本库用户名', max_length=50, blank=True, null=True)
    vcs_password = models.CharField(u'版本库密码', max_length=50, blank=True, null=True)
    db_type = models.CharField(u'数据库类型', choices=DB_TYPE_CHOICES, default='mysql', max_length=20, blank=True, null=True)
    db_host = models.CharField(u'数据库HOST', max_length=1024, blank=True, null=True)
    db_port = models.IntegerField(u'数据库PORT', default=3306, blank=True, null=True)
    db_name = models.CharField(u'数据库名称', max_length=30, blank=True, null=True)
    db_username = models.CharField(u'数据库用户名', max_length=50, blank=True, null=True)
    db_password = models.CharField(u'数据库密码', max_length=50, blank=True, null=True)

    @property
    def vcs_type_text(self):
        text = dict(VCS_TYPE_CHOICES).get(self.vcs_type)
        if not text:
            return 'unknow'
        return text.lower()

    def __unicode__(self):
        return self.app_code

    class Meta:
        db_table = 'paas_app_secureinfo'
        verbose_name = u'应用安全相关信息'
        verbose_name_plural = u'应用安全相关信息'
